package com.xing.web.advice;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created by Bradish7Y on 2017/8/23.
 * 拦截controller统一错误
 */
@ControllerAdvice
public class GlobalExceptionController {

    public static final Logger log = LoggerFactory.getLogger(GlobalExceptionController.class);


    @ExceptionHandler({RuntimeException.class})
    @ResponseStatus(HttpStatus.OK)
    public ModelAndView processException(RuntimeException exception) {
        log.info("自定义异常处理-RuntimeException");
        ModelAndView m = new ModelAndView("error/error");
        m.addObject("msg", exception);
        return m;
    }


    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public ModelAndView exception(Exception ex) {//不可以用Model model，报错
        ModelAndView mv = new ModelAndView("error/error");//ftl页面
        mv.addObject("msg", ex);

        log.error("error", ex);

        return mv;

    }

//    @ExceptionHandler(value=MethodArgumentNotValidException.class)
//    public Object MethodArgumentNotValidHandler(HttpServletRequest request,
//                                                MethodArgumentNotValidException exception) throws Exception
//    {
//        //按需重新封装需要返回的错误信息
//        List<ArgumentInvalidResult> invalidArguments = new ArrayList<>();
//        //解析原错误信息，封装后返回，此处返回非法的字段名称，原始值，错误信息
//        for (FieldError error : exception.getBindingResult().getFieldErrors()) {
//            ArgumentInvalidResult invalidArgument = new ArgumentInvalidResult();
//            invalidArgument.setDefaultMessage(error.getDefaultMessage());
//            invalidArgument.setField(error.getField());
//            invalidArgument.setRejectedValue(error.getRejectedValue());
//            invalidArguments.add(invalidArgument);
//        }
//
//        ResultMsg resultMsg = new ResultMsg(ResultStatusCode.PARAMETER_ERROR.getErrcode(), ResultStatusCode.PARAMETER_ERROR.getErrmsg(), invalidArguments);
//        return resultMsg;
//    }
}
